package com.ndp.fb.creative.fetchdata.dao.mongodb.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.ndp.fb.creative.fetchdata.dao.domain.SumResult;
import com.ndp.fb.creative.fetchdata.dao.mongodb.HashcodeSumMongoService;
import com.ndp.fb.creative.fetchdata.dao.mongodb.MongodbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Evan on 2015/5/21 22:02.
 * Email evan.wan@ndpmedia.com
 */
@Service
public class HashcodeSumMongoServiceImpl implements HashcodeSumMongoService
{
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${spring.data.mongodb.tablename}")
    private String tablename;

    @Autowired
    private DB mongoDBClient;

    @Autowired
    private MongodbUtils mongodbUtils;

    @Override
    public List<SumResult> find(List<Long> adGroupIds)
    {
        List<DBObject> pipeline = new ArrayList<DBObject>();
        DBObject matchObject = new BasicDBObject();
        matchObject.put("adGroupId", new BasicDBObject("$in", adGroupIds.toArray(new Object[adGroupIds.size()])));
        DBObject match = new BasicDBObject();
        match.put("$match", matchObject);
        pipeline.add(match);
        //构建统计对象
        DBObject sumImpressions = new BasicDBObject();
        sumImpressions.put("$sum", "$impressions");
        DBObject sumClicks = new BasicDBObject();
        sumClicks.put("$sum", "$clicks");
        DBObject sumResults = new BasicDBObject();
        sumResults.put("$sum", "$results");
        DBObject sumSpent = new BasicDBObject();
        sumSpent.put("$sum", "$spent");

        DBObject groupObj = new BasicDBObject();
        groupObj.put("imageHash", "$imageHash");
        groupObj.put("adGroupId", "$adGroupId");
        groupObj.put("day", "$day");
        DBObject group = new BasicDBObject();
        group.put("_id", groupObj);
        //group.put("imageHash", "$imageHash");
        group.put("impressions", sumImpressions);
        group.put("clicks", sumClicks);
        group.put("results", sumResults);
        group.put("spent", sumSpent);

        DBObject param2 = new BasicDBObject();
        param2.put("$group", group);
        pipeline.add(param2);

        Long start = System.currentTimeMillis();
        logger.info("pipeline"+JSON.toJSONString(pipeline));
        AggregationOutput out = mongoDBClient.getCollection(tablename).aggregate(pipeline);
        List<SumResult> res = new ArrayList<>();
        Iterator<DBObject> iterator = out.results().iterator();
        DBObject dbObject;
        while(iterator.hasNext()){
            dbObject = iterator.next();
            dbObject.put("day", ((DBObject)dbObject.get("_id")).get("day"));
            dbObject.put("imageHash", ((DBObject)dbObject.get("_id")).get("imageHash"));
            dbObject.put("adGroupId", ((DBObject)dbObject.get("_id")).get("adGroupId"));
            res.add(JSONObject.parseObject(JSON.toJSONString(dbObject), SumResult.class));
        }
        logger.info("获取总花费耗时：" + (System.currentTimeMillis() - start));

        return res;
    }

}
